package com.cbs.android.function.input;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.cbs.android.component.application.activity.CBSDialogFragment;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zyj on 2016/3/19.
 */
public class SelectDialogFragment extends CBSDialogFragment {
	private List<String> items = null;
	private String selecter = null;
	private String title;
	private OnConfirmListener onConfirmListener;
	private int layout = R.layout.cbs_input_dialog_select;
	private List<Integer> ids = new ArrayList<>();

	private RadioGroup radioGroup;

	public SelectDialogFragment setTitle(String title) {
		this.title = title;
		return this;
	}

	public SelectDialogFragment setItems(List<String> items) {
		this.items = items;
		return this;
	}

	public SelectDialogFragment setSelecter(String selecter) {
		this.selecter = selecter;
		return this;
	}

	public SelectDialogFragment setOnConfirmListener(OnConfirmListener onConfirmListener) {
		this.onConfirmListener = onConfirmListener;
		return this;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		View view = inflater.inflate(layout, container, false);

		// TODO need to check all code below
		// TODO layout
		TextView titleView = (TextView) view.findViewById(R.id.cbs_input_dialog_select_title);

		radioGroup = (RadioGroup) view.findViewById(R.id.cbs_input_dialog_select_group);
		if (items != null && items.size() > 0) {
			for (int i = 0; i < items.size(); i++) {
				RadioButton radioButton = (RadioButton) inflater.inflate(R.layout.cbs_input_dialog_select_radiobutton, radioGroup, false);
				radioButton.setText(items.get(i));
				radioButton.setId(i);
				ids.add(i);
				radioGroup.addView(radioButton);
			}
		}

		if (selecter != null && items.contains(selecter)) {
			int i = items.indexOf(selecter);
			radioGroup.check(ids.get(i));
		}

		titleView.setText(title);

		Button cancelView = (Button) view.findViewById(R.id.cbs_input_dialog_select_cancel);
		Button submitView = (Button) view.findViewById(R.id.cbs_input_dialog_select_submit);
		cancelView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				onCancelListener.onClick(SelectDialogFragment.this);
			}
		});
		submitView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				int i = ids.indexOf(radioGroup.getCheckedRadioButtonId());
				onConfirmListener.onConfirm(SelectDialogFragment.this, i, items.get(i));
			}
		});
		return view;
	}

	public interface OnConfirmListener {
		void onConfirm(CBSDialogFragment dialogFragment, int i, String select);
	}

}
